function handles = analysisHandler(handles)
% analysisHandler
%
% Manages analysis of variable numbers of maps
%
% Editing:
% gs april 2005
% % ----------------------------------------------------

handles.data.analysis.cellAttachedCheck = 0;
% Note: this is basically a flag, indicating that we're not in EP analysis mode

% reset the analysis stack
handles = mapStacker(handles, 'reset');

% reset other stuff
handles = resetAnalysis('reanalyze', handles);

% loop through the individual map trials
for m = 1 : handles.data.analysis.numberOfMaps
    
    string = (['handles.data.map.map' num2str(m)]);
    eval(['handles.data.map.mapActive = ' string ';']);
    
    handles = analyzeInputMapArray(handles);
    
    % add the map data to the analysis stack
    mode = 'add';
    handles = mapStacker(handles, mode);    
    
    handles.data.map.mapAvg.synThreshpAmV = [handles.data.map.mapAvg.synThreshpAmV    handles.data.map.mapActive.synThreshpAmV];
    handles.data.map.mapAvg.baselineSD = [handles.data.map.mapAvg.baselineSD    handles.data.map.mapActive.baselineSD];
    handles.data.map.mapAvg.spontEventRate = [handles.data.map.mapAvg.spontEventRate    handles.data.map.mapActive.spontEventRate];
    
    eval([string ' = handles.data.map.mapActive;']);
end

% avg and update certain analysis results in the gui
handles.data.map.mapAvg.synThreshpAmV = mean(handles.data.map.mapAvg.synThreshpAmV);
handles.data.map.mapAvg.baselineSD = mean(handles.data.map.mapAvg.baselineSD);
handles.data.map.mapAvg.spontEventRate = mean(handles.data.map.mapAvg.spontEventRate);

set(handles.synThreshpAmV, 'String', num2str(round(100*handles.data.map.mapAvg.synThreshpAmV)/100));
set(handles.baselineSD, 'String', num2str(round(100*handles.data.map.mapAvg.baselineSD)/100));
set(handles.spontEventRate, 'String', num2str(round(100*handles.data.map.mapAvg.spontEventRate)/100));

% avg and plot the maps
mode = 'mean';
handles = mapStacker(handles, mode);
if ~isempty(handles.data.map.mapStack.mapAvgMin)
    %     if get(handles.chkShowHistoAnalysis, 'Value');
    handles = ampHistoAnalysis(handles);
    %     end
    arrayAvgPlots(handles);
else
    beep
    disp('processSetFamily: No average maps available for plotting.')
end

s = -sum(handles.data.map.mapStack.mapStackHistoThresh, 3);
s(isnan(s))=inf;
disp('map.eventNumSum = [');
disp(s);
disp('];');
handles.data.map.mapStack.mapAvgEventNumSum = abs(s);
% TODO: consolidate improve the dump-to-command-window 

% avg cell params
if get(handles.chkWithRsRm, 'Value')
    handles = avgCellParameters(handles);
end

% fourth window analysis
if get(handles.fourthWindowMaps, 'Value')
    fourthWindowMaps(handles);
end
